package cn.itcast.httpclient;

import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

public class DoGET {

    public static void main(String[] args) throws Exception {

        // 创建Httpclient对象，相当于打开浏览器
        CloseableHttpClient httpclient = HttpClients.createDefault();

        // 创建httpGet请求，相当于在浏览器输入地址
        HttpGet httpGet = new HttpGet("http://www.baidu.com");

        CloseableHttpResponse response = null;
        try {
            // 执行请求，相当于敲完地址后按下回车。获取响应
            response = httpclient.execute(httpGet);
            // 判断响应状态是否为200
            if (response.getStatusLine().getStatusCode() == 200) {
            	// 解析响应获取数据
                String content = EntityUtils.toString(response.getEntity(), "UTF-8");
                System.out.println(content);
            }
        } finally {
            if (response != null) {
            	// 关闭资源
                response.close();
            }
            // 关闭httpclient对象，相当于关闭浏览器
            httpclient.close();
        }
    }
}
